<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
            <el-form-item label="合同版本号" prop="contractVersion">
                <el-input v-model="queryParams.contractVersion" placeholder="请输入合同版本号"
                          clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="合同编号" prop="contractNo">
                <el-input v-model="queryParams.contractNo" placeholder="请输入合同编号"
                        clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="添加时间">
                <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                                type="datetimerange" range-separator="-" :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期" end-placeholder="结束日期"/>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select
                    v-model="queryParams.status"
                    placeholder="请输入状态"
                    clearable
                    size="small"
                    style="width: 240px"
                >
                    <el-option
                        v-for="dict in sysStatus"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['bs:contract:saveOrUpdate']"
                >新增</el-button>
            </el-col>
        </el-row>
        <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
            <el-table-column label="ID" align="center" prop="id" :show-overflow-tooltip="true" />
            <el-table-column label="合同版本号" align="center" prop="contractVersion" :show-overflow-tooltip="true" />
            <el-table-column label="甲方信息" align="center" prop="oneDesc" :show-overflow-tooltip="true" />
<!--            <el-table-column label="甲方签章" align="center" prop="oneImg" :show-overflow-tooltip="true" >-->
<!--                <template slot-scope="scope">-->
<!--                    <el-image-->
<!--                        style="width: 50px; height: 50px"-->
<!--                        :src="baseImgUrl + scope.row.oneImg"-->
<!--                    >-->
<!--                    </el-image>-->
<!--                </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column label="乙方信息" align="center" prop="twoDesc" :show-overflow-tooltip="true" />-->
            <el-table-column label="合同文本" align="center" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span class="link-type" @click="handleShow(scope.row)">
                        查看合同
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="合同编号" align="center" prop="contractNo" :show-overflow-tooltip="true" />
            <el-table-column label="添加时间" align="center" prop="createTime" width="180" />
            <el-table-column label="状态" align="center" prop="status" width="100">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
<!--                    <el-button size="mini" type="text" icon="el-icon-view" @click="handleShow(scope.row)"-->
<!--                            v-hasPermi="['bs:contract:saveOrUpdate']">预览</el-button>-->
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                            v-hasPermi="['bs:contract:saveOrUpdate']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                            v-hasPermi="['bs:contract:delete']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.nowPage" :limit.sync="queryParams.pageSize" @pagination="getPage"/>
        <!-- 查看合同对话框 -->
        <el-dialog :title="title" :visible.sync="showOpen" width="800px"  v-dialog-drag :close-on-click-modal='false'>
            <div class="docx-preview">
                <vue-office-docx :src="docxUrl" />
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelShow">关闭</el-button>
            </div>
        </el-dialog>
        <!-- 添加或修改合同管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px"  v-dialog-drag :close-on-click-modal='false'>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="合同版本号" prop="contractVersion">
                    <el-input v-model="form.contractVersion" :style="{width: '100%'}"  type="text" placeholder="请输入合同版本号" />
                </el-form-item>
                <el-form-item label="收益周期" prop="times">
                    <el-input v-model="form.times" :style="{width: '100%'}"  type="text" placeholder="请输入收益周期" />
                </el-form-item>
                <el-form-item label="甲方账户信息" prop="oneDesc">
                    <el-input v-model="form.oneDesc" type="textarea" placeholder="账户名称|银行卡号|开户银行"
                              :autosize="{minRows: 1, maxRows: 10}" :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="合同文本" prop="contractContent">
                    <el-upload ref="upload" :limit="1" accept=".docx" :headers="upload.headers"
                               :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                               :show-file-list="true" :file-list="fileList"
                               :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="true" drag>
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">
                            将文件拖到此处，或
                            <em>点击上传</em>
                        </div>
                        <div class="el-upload__tip" slot="tip">
                            <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
                        </div>
                        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“docx”格式文件！</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="合同编号" prop="contractNo">
                    <el-input v-model="form.contractNo" :style="{width: '100%'}"  type="text" placeholder="请输入合同编号" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status" :style="{width: '100%'}">
                        <el-radio
                            v-for="dict in sysStatus"
                            :key="dict.dictValue"
                            :label="dict.dictValue"
                        >{{dict.dictLabel}}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {getBsContractPage,getBsContractById,addOrUpdateBsContract,delBsContract,exportBsContract} from "@/api/project/bsContract/bsContract";
import Editor from '@/components/Editor';
import imageUpload from '@/components/ImageUpload';
import VueOfficeDocx from '@vue-office/docx'
import {getToken} from "@/utils/auth";
import {download} from "@/utils/ruoyi";

export default {
    name: "bsContract",
    components: {
        Editor,
        imageUpload,
        VueOfficeDocx
    },
    data() {
        return {
            docxUrl: '',
            baseImgUrl: process.env.VUE_APP_BASE_API, // 图片URL
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 参数表格数据
            configList: [],
            // 弹出层标题
            title: "",
            open: false,// 是否显示修改或增加的弹出层
            // 日期范围
            dateRange: [],
            // 状态数据字典
            sysStatus: [],
            // 查询参数
            queryParams: {
                nowPage: 1,
                pageSize: 10,
                contractContent: undefined,
                contractNo: undefined,
                contractVersion: undefined,
                createBy: undefined,
                oneDesc: undefined,
                oneImg: undefined,
                status: undefined,
                twoDesc: undefined,
                updateBy: undefined,
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: {
                    Authorization: "Bearer " + getToken()
                },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/common/upload"
            },
            fileList: [],
            // 表单参数
            form: {},
            showOpen: false,//是否显示查看工作内容弹出层
            showForm: {},
            // 表单校验
            rules: {
                times: [
                    {required: true, message: "收益周期不能为空", trigger: "blur"}
                ],
                contractContent: [
                    {required: true, message: "合同文本不能为空", trigger: "blur"}
                ],
                contractNo: [
                    {required: true, message: "合同编号不能为空", trigger: "blur"}
                ],
                contractVersion: [
                    {required: true, message: "合同版本号不能为空", trigger: "blur"}
                ],
                oneDesc: [
                    {required: true, message: "甲方信息不能为空", trigger: "blur"}
                ],
                status: [
                    {required: true, message: "状态（0启用/1停用）不能为空", trigger: "blur"}
                ]
            },
        };
    },
    created() {
        this.getPage();
        this.getDicts("sys_normal_disable").then(response => {
            this.sysStatus = response.data;
        });
    },
    methods: {
        /** 查询参数列表 */
        getPage(e) {
            this.loading = true;
            let contractContent = this.queryParams.contractContent || '';
            let contractNo = this.queryParams.contractNo || '';
            let contractVersion = this.queryParams.contractVersion || '';
            let createBy = this.queryParams.createBy || '';
            let oneDesc = this.queryParams.oneDesc || '';
            let oneImg = this.queryParams.oneImg || '';
            let status = this.queryParams.status || '';
            let twoDesc = this.queryParams.twoDesc || '';
            let updateBy = this.queryParams.updateBy || '';
            let time = this.dateRange || '';
            let params = '';
            if (e) {
                params = {
                    contractContent: contractContent,
                    contractNo: contractNo,
                    contractVersion: contractVersion,
                    createBy: createBy,
                    oneDesc: oneDesc,
                    oneImg: oneImg,
                    status: status,
                    twoDesc: twoDesc,
                    updateBy: updateBy,
                    startTime: time[0],
                    endTime: time[1],
                    nowPage: e.page,
                    pageSize: e.limit
                }
            } else {
                params = {
                    contractContent: contractContent,
                    contractNo: contractNo,
                    contractVersion: contractVersion,
                    createBy: createBy,
                    oneDesc: oneDesc,
                    oneImg: oneImg,
                    status: status,
                    twoDesc: twoDesc,
                    updateBy: updateBy,
                    startTime: time[0],
                    endTime: time[1],
                    nowPage: this.queryParams.nowPage,
                    pageSize: this.queryParams.pageSize
                }
            }
            getBsContractPage(params).then(response => {
                this.configList = response.data.records;
                this.total = response.data.total;
                this.loading = false;
            })
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                contractContent: undefined,
                contractNo: undefined,
                contractVersion: undefined,
                createBy: undefined,
                createTime: undefined,
                oneDesc: undefined,
                oneImg: undefined,
                status: undefined,
                twoDesc: undefined,
                updateBy: undefined,
                updateTime: undefined,
            };
            this.showForm = {
                contractContent: undefined,
                contractNo: undefined,
                contractVersion: undefined,
                createBy: undefined,
                createTime: undefined,
                oneDesc: undefined,
                oneImg: undefined,
                status: undefined,
                twoDesc: undefined,
                updateBy: undefined,
                updateTime: undefined,
            };
            this.resetForm("form");
            this.resetForm("showForm");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            let contractContent = this.queryParams.contractContent || '';
            let contractNo = this.queryParams.contractNo || '';
            let contractVersion = this.queryParams.contractVersion || '';
            let createBy = this.queryParams.createBy || '';
            let oneDesc = this.queryParams.oneDesc || '';
            let oneImg = this.queryParams.oneImg || '';
            let status = this.queryParams.status || '';
            let twoDesc = this.queryParams.twoDesc || '';
            let updateBy = this.queryParams.updateBy || '';
            let time = this.dateRange || '';
            let params = {
                contractContent: contractContent,
                contractNo: contractNo,
                contractVersion: contractVersion,
                createBy: createBy,
                oneDesc: oneDesc,
                oneImg: oneImg,
                status: status,
                twoDesc: twoDesc,
                updateBy: updateBy,
                startTime: time[0],
                endTime: time[1],
                nowPage: 1,
                pageSize: this.queryParams.pageSize
            };
            getBsContractPage(params).then(res => {
                if (res.code == 200) {
                    this.configList = res.data.records;
                    this.total = res.data.total;
                    this.loading = false;
                }
            })
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.queryParams.contractContent = '';
            this.queryParams.contractNo = '';
            this.queryParams.contractVersion = '';
            this.queryParams.createBy = '';
            this.queryParams.oneDesc = '';
            this.queryParams.oneImg = '';
            this.queryParams.status = '';
            this.queryParams.twoDesc = '';
            this.queryParams.updateBy = '';
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.form.status = '0';
            this.fileList = [];
            this.open = true;
            this.title = "添加合同管理信息";
        },
        //多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length != 1;
            this.multiple = !selection.length
        },
        /** 查看按钮操作 */
        handleShow(row) {
            this.reset();
            const id = row.id || '';
            getBsContractById({id}).then(response => {
                this.showForm = response.data;
                this.showOpen = true;
                this.docxUrl = this.baseImgUrl + this.showForm.contractContent;
                this.title = "合同";
            });
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.fileList = [];
            const id = row.id || '';
            getBsContractById({id}).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改合同管理信息";
            });
        },
        cancelShow: function () {
            this.showOpen = false;
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id !== undefined) {
                        addOrUpdateBsContract(this.form).then(res => {
                            if (res.code == 200) {
                                this.msgSuccess("修改成功");
                                this.open = false;
                                this.getPage();
                            } else {
                                this.msgError(res.msg);
                            }
                        })
                    } else {
                        addOrUpdateBsContract(this.form).then(res => {
                            if (res.code == 200) {
                                this.msgSuccess("新增成功");
                                this.open = false;
                                this.getPage();
                            } else {
                                this.msgError(res.msg);
                            }
                        })
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除合同管理编号为"' + ids + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delBsContract(ids);
            }).then(() => {
                this.getPage();
                this.msgSuccess("删除成功");
            }).catch(function () {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有合同管理数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return exportBsContract(queryParams);
            }).then(res => {
                this.download(res.data);
            }).catch(function () {
            });
        },
        /** 状态修改 */
        handleStatusChange(row) {
            let text = row.status === "0" ? "停用" : "启用";
            this.$confirm('确认要"' + text + '""' + row.contractNo + '"吗?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function() {
                return addOrUpdateBsContract(row);
            }).then(() => {
                this.msgSuccess(text + "成功");
            }).catch(function() {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
        /** 下载模板操作 */
        importTemplate() {
            download("template.docx");
        },
        /** 文件上传中处理 */
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        /** 文件上传成功处理 */
        handleFileSuccess(response, file, fileList) {
            this.upload.isUploading = false;
            this.fileList.push({
                name: response.originalFilename,
                url: this.baseImgUrl + response.url,
                resultUrl: response.url
            });
            this.form.contractContent = response.url;
        },
    }
};
</script>
<style>

</style>
